package com.guigu.guligateway.config;

import com.guigu.gulicommon.entity.pojo.res.Res;
import com.guigu.gulicommon.tools.JwtTool;
import com.guigu.guligateway.properties.AuthProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Objects;

import static com.guigu.gulicommon.constant.RedisKey.USER_INFO_PREFIX;
import static com.guigu.gulicommon.constant.enumes.res.AuthResCode.*;

/**
 * jwt过滤器
 *
 * @author 陈俊杰
 * @version 1.0
 * @since 2024/8/14 16:09
 */
@Log4j2
@Component
public class JwtGlobalFilterConfig implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private AuthProperties authProperties;

    /**
     * @param exchange 请求
     * @param chain    过滤器
     * @return 响应
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 检查是否为放行的URL
        ServerHttpRequest request = exchange.getRequest();
        if (isPermittedUrl(request)) {
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        //1 设置 HTTP 状态码
        response.setStatusCode(HttpStatus.OK);
        //2 设置响应体格式
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        //3 获取请求头中的token,进行校验
        List<String> tokens = exchange.getRequest().getHeaders().get("token");
        if (tokens == null || tokens.isEmpty()) {
            //3.1 token不存在时返回前端信息
            //3.1.1 创建错误响应对象
            Res<Object> res = new Res<>(LOGIN_INFORMATION_DOES_NOT_EXIST);
            //3.1.2 返回登陆不存在的信息
            return response.writeWith(Mono.just(response.bufferFactory().wrap(res.toJson().getBytes())));
        }
        String token = tokens.get(0);
        //3.2 存在时,校验合法性
        switch (JwtTool.verify(token, authProperties.getJwt().getSecret())) {
            case 0:
                //3.2.1 合法时,进行下一步;
                break;
            case 1:
                //3.2.2 返回登陆过期的信息
                Res<Object> res = new Res<>(LOGIN_EXPIRED);
                return response.writeWith(Mono.just(response.bufferFactory().wrap(res.toJson().getBytes())));
            case 2:
                //3.2.3 返回登陆无效的信息
                Res<Object> res2 = new Res<>(AUTHENTICATION_FAIL);
                return response.writeWith(Mono.just(response.bufferFactory().wrap(res2.toJson().getBytes())));
            default:
                //3.2.4 返回登陆无效的信息
                Res<Object> res3 = new Res<>(AUTHENTICATION_FAIL);
                return response.writeWith(Mono.just(response.bufferFactory().wrap(res3.toJson().getBytes())));
        }
        //3.3 比对redis中是否有这个登陆信息
        //3.3.1 从token载荷中获取用户id
        String userId = JwtTool.getLoad(token);
        //3.3.2 根据用户id查询redis中的信息是否存在
        if (!Objects.equals(redisTemplate.opsForHash().get(USER_INFO_PREFIX + userId, "token"), token)) {
            //3.3.3 不存在时,返回登陆过期的信息
            Res<Object> res = new Res<>(LOGIN_INFORMATION_DOES_NOT_EXIST);
            return response.writeWith(Mono.just(response.bufferFactory().wrap(res.toJson().getBytes())));
        }
        //4 把解析到的用户id放在请求头中,供下游服务使用
        request.mutate().header("gulimall-userId", userId);
        return chain.filter(exchange);
    }

    private boolean isPermittedUrl(ServerHttpRequest request) {
        // 检查请求是否针对不需要认证的路径
        URI uri = request.getURI();
        String path = uri.getPath();
        return authProperties.getNotNeedTokenPaths().stream().anyMatch(path::endsWith);
    }

    /**
     * @return 优先级
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
